package com.andaily.domain.thing.handler;

import com.andaily.domain.shared.DateUtils;
import com.andaily.domain.thing.Thing;
import com.andaily.domain.thing.ThingRepository;
import com.andaily.domain.thing.ThingStatus;
import com.andaily.domain.user.User;
import com.andaily.infrastructure.support.LogHelper;
import com.andaily.web.context.BeanProvider;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Date: 13-7-19
 *
 * @author Shengzhao Li
 */
public class UserAutoStartThingHandler {

    private static LogHelper log = LogHelper.create(UserAutoStartThingHandler.class);

    private transient ThingRepository thingRepository = BeanProvider.getBean(ThingRepository.class);
    private final Date today;

    public UserAutoStartThingHandler() {
        this.today = DateUtils.now();
    }

    /**
     * To per Thing:
     * 1. Change status to PENDING , set auto pending by scheduler is true
     * 2. Send notify email to user
     *
     * @param user user
     */
    public void handle(User user) {
        Date nextDay = nextDay();
        List<Thing> availableThings = thingRepository.findStartTimeThings(user, new java.sql.Date(nextDay.getTime()));
        if (availableThings.isEmpty()) {
            log.debug("Not found any CREATED things by user: " + user + ", ignore handle");
            return;
        }
        changeThings(availableThings);

        //send notify email
        AutoStartThingMailHandler autoStartThingMailHandler = new AutoStartThingMailHandler(user, availableThings, nextDay);
        autoStartThingMailHandler.handle();
    }

    private void changeThings(List<Thing> availableThings) {
        //update status
        thingRepository.updateThingsStatus(availableThings, ThingStatus.PENDING);
        // set auto pending by scheduler
        thingRepository.updateThingsAutoPendingByScheduler(availableThings, true);
    }

    private Date nextDay() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(today);
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        return calendar.getTime();
    }
}
